import dayjs from 'dayjs';
/**
 * 获取授权文件名称
 * @param fileName 原始文件名
 * @param deadline 授权截止日期
 * @param withDeadline  是否含授权截止日期
 */
const downloadFileName = (fileName: string, deadline: string, withDeadline: boolean = false) => {
  if (withDeadline) {
    const ext = `.${fileName.split('.').pop()}`;
    const basename = fileName.replace(ext, '');
    return `${basename}_${deadline}${ext}`;
  }
  return fileName.replace(`_${deadline}`, '');
};

/**
 * 计算获取时间标签
 * @param deadline 授权截止时间
 */
const calcTimeTag = (deadline?: string) => {
  if (deadline) {
    const d = deadline.replace(/(\d{4})(\d{2})(\d{2})/, '$1/$2/$3');
    const now = dayjs(new Date()).format('YYYY/MM/DD');
    const year = dayjs(d).diff(now, 'year');
    if (year > 0) {
      return `${year}Y`;
    }
    const month = dayjs(d).diff(now, 'month');
    if (month > 0) {
      return `${month}M`;
    }
    const week = dayjs(d).diff(now, 'week');
    if (week > 1 && week < 5) {
      return `${week}W`;
    }
    const day = dayjs(d).diff(now, 'day');
    if (day > 1 && day < 7) {
      return `${day}D`;
    }
  }
  return '7D';
};

/**
 * 字符串转 Uint8Array
 * @param text
 */
const string2Uint8Array = (text: string) => {
  const bytes = text.split('').map((c) => c.charCodeAt(0));
  return new Uint8Array(bytes);
};

/**
 * Uint8Array 转字符串
 * @param arr
 */
const uint8Array2String = (arr: Uint8Array) => {
  const result: string[] = [];
  arr.forEach((v) => result.push(String.fromCharCode(v)));
  return result.join();
};

export { downloadFileName, calcTimeTag, string2Uint8Array, uint8Array2String };
